package org.rc.server;

import lombok.extern.slf4j.Slf4j;
import org.rc.cache.RemoteRoleTextSessionCache;
import org.rc.config.WsSessionConfig;
import org.rc.entity.Mic;
import org.rc.entity.RoomDev;
import org.rc.enums.DevType;
import org.rc.service.MicService;
import org.rc.service.RoomDevService;
import org.rc.util.RequestParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Slf4j
@ServerEndpoint(value = "/role-text",configurator = WsSessionConfig.class)
@Component
@Scope("prototype")
public class RemoteRoleTextEndpoint {

    @Autowired
    private RoomDevService roomDevService;

    @Autowired
    private MicService micService;

    @OnOpen
    public void onOpen(Session session, EndpointConfig config) throws IOException {
        String param = session.getQueryString();
        Map<String,String> paramsMap = RequestParamUtil.regularParam2Map(param);
        String roomId = paramsMap.get("roomId");
        log.info("接收到远程指挥角色分离连接，roomId --->{}",roomId);
        List<RoomDev> roomDev = roomDevService.getRoomDevByRoomIdAndDevId(DevType.MIC.getType(),Long.parseLong(roomId));
        if(CollectionUtils.isEmpty(roomDev)){
            log.warn("当前房间尚未绑定麦克风，断开连接");
            session.getBasicRemote().sendText("当前房间尚未绑定麦克风，断开连接");
            session.close();
            return;
        }
        Mic mic = micService.getByMicId(roomDev.get(0).getDevId());
        String mac = mic.getMac();
        session.getUserProperties().put("mac",mac);
        RemoteRoleTextSessionCache.add(mac,session);

    }

    @OnMessage
    public void onMessage(String text, Session session) throws IOException {

    }

    @OnClose
    public void onClose(Session session){
        log.info("======断开连接=====");
        String mac = session.getUserProperties().get("mac").toString();
        RemoteRoleTextSessionCache.removeSession(mac,session);
    }

    @OnError
    public void onError(Session session, Throwable th){
        log.error("连接发生异常，e--->",th);
        String mac = session.getUserProperties().get("mac").toString();
        RemoteRoleTextSessionCache.removeSession(mac,session);
    }
}
